package com.example.demo.common;

import com.example.demo.domain.entity.User;
import com.example.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import java.util.List;

import static com.example.demo.constant.ApplicationConstant.KEY;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    DataSource dataSource;

    @GetMapping("/login")
    public ResponseEntity<String> userLogin(
            @RequestParam String name,
            @RequestParam String passWord,
            HttpServletRequest request) {
        HttpSession session = request.getSession();
        Integer id = userService.login(name, passWord);
        if (id == null) {
            return ResponseEntity.badRequest().body("用户名或者密码错误");
        }
        session.setAttribute(KEY, name);
        return ResponseEntity.ok("登录成功");
    }

    @GetMapping("/login/error")
    public ResponseEntity<String> loginError() {
        return ResponseEntity.badRequest().body("请先登录后再访问");
    }

    /**
     * 插入测试数据
     */
    @GetMapping("/test")
    public void insertTestData() {
        for (int i = 0; i < 500; i++) {
            userService.insertTestData();
        }
    }

    /**
     * 查询用户的兴趣爱好
     * 延迟加载测试
     */
    @GetMapping("/info")
    public List<User> findUserInfo(){
        List<User> users =  userService.findUserInfo();
        //下面将查询第一个用户的信息
        log.info("user: {}", users.get(0).getUserInfoList());
        //返回user，会查询所有用户信息
        return users;
    }

}
